<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
    <!-- 内容区域 -->
    <div class="p-6 bg-gray-100 flex-1">
        <div class="bg-white rounded-lg p-6">
            <!-- 搜索区域 -->
            <div class="mb-4" style="box-shadow: none;--el-card-border-color: none; padding: 0">
                <div style="display: flex;justify-content: space-between">
                    <div class="flex flex-wrap gap-4">
                        <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" class="!w-64" clearable />
                        <el-input v-model="searchForm.roleKey" placeholder="请输入权限字符" class="!w-64" clearable />
                        <el-select v-model="searchForm.status" placeholder="角色状态" class="!w-64" clearable>
                            <el-option label="正常" value="1" />
                            <el-option label="停用" value="0" />
                        </el-select>
                    </div>
                    <div class="flex justify-end  space-x-4">
                        <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="handleSearch">
                            <el-icon class="mr-1">
                                <Search />
                            </el-icon>搜索
                        </el-button>
                        <el-button class="!rounded-button whitespace-nowrap" @click="resetSearch">
                            <el-icon class="mr-1">
                                <Refresh />
                            </el-icon>重置
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 操作按钮区 -->
            <div class="mb-4 flex justify-between">
                <div class="space-x-2">
                    <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>新增
                    </el-button>
                    <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>删除
                    </el-button>
                </div>
            </div>

            <!-- 表格 -->
            <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="角色编号" prop="roleId" width="120" />
                <el-table-column label="角色名称" prop="roleName" width="200" />
                <el-table-column label="权限字符" prop="roleKey" width="200" />
                <el-table-column label="显示顺序" prop="roleSort" width="120" />
                <el-table-column label="状态" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" :formatter="formatDate"/>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="primary" link @click="openDialog('edit', scope.row)">修改</el-button>
                        <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="mt-4 flex items-center justify-end">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" />
            </div>
        </div>

    </div>
     <!-- 新增/编辑用户弹窗 -->
     <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="权限字符" prop="roleKey">
                <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
            </el-form-item>
            <el-form-item label="显示顺序" prop="roleSort">
                <el-input v-model="form.roleSort" placeholder="请输入显示顺序" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit(formRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";


import {
    HomeFilled,
    Setting,
    User,
    UserFilled,
    Search,
    Bell,
    FullScreen,
    Plus,
    Edit,
    Delete,
    Download,
    Refresh
} from '@element-plus/icons-vue';

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};

// 选中的行的ID数组
const selectedRowKeys = ref([]);

const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};

// 重置搜索表单
const resetSearch = () => {
  searchForm.value = {
    roleName: "",
    roleKey: "",
    status: "",
  };
  // 这里可以根据需要重新加载表格数据
};
//搜索栏内容
const searchForm = ref({
    roleName: '',
    roleKey: '',
    status: '',
    dateRange: []
});

//表格内容
const tableData = ref([
    {
        roleId: 1,
        roleName: '超级管理员',
        roleKey: 'admin',
        roleSort: 1,
        status: 1,
        createTime: '2024-01-15 10:00:00'
    },
    {
        roleId: 2,
        roleName: '学生',
        roleKey: 'common',
        roleSort: 2,
        status: 1,
        createTime: '2024-01-15 10:00:00'
    },
    {
        roleId: 3,
        roleName: '学校管理员',
        roleKey: 'common',
        roleSort: 2,
        status: 1,
        createTime: '2024-01-15 10:00:00'
    },
    {
        roleId: 4,
        roleName: '教师',
        roleKey: 'common',
        roleSort: 2,
        status: 1,
        createTime: '2024-01-15 10:00:00'
    }
]);

//分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(2);
//分页

//搜索
const handleSearch = () => {
    console.log('搜索');
};

//新增角色内容
// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
const form = ref({
    rolename: '',
    roleKey: '',
    roleSort: '',
    status: true
});



const openDialog = (type: string, row?: any) => {
    dialogType.value = type;
    dialogVisible.value = true;
    if (type === 'edit' && row) {
        Object.assign(form, row);
    } else {
        Object.keys(form).forEach(key => {
            form[key as keyof typeof form] = '';
        });
        form.status = true;
    }
};

//提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            console.log('提交表单', form);
            dialogVisible.value = false;
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功');
        }
    });
};

//删除
const handleDelete = (row: any) => {
    // 获取当前选中的行
   const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));
    
    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 模拟删除操作
        selectedRows.forEach(row => {
            tableData.value = tableData.value.filter(item => item.id !== row.id);
        });
        ElMessage.success('删除成功');
    }).catch(() => { });
};
</script>

<style scoped>
.el-input {
    --el-input-border-color: #dcdfe6;
}

.el-date-editor {
    --el-datepicker-border-color: #dcdfe6;
}

:deep(.el-table) {
    --el-table-border-color: #dcdfe6;
    --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-pagination) {
    --el-pagination-button-bg-color: #fff;
    --el-pagination-hover-color: #409eff;
}

.el-card__body {
    padding: 0;
}
</style>

